package com.citcc.api.netty.server;


import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

import com.citcc.api.netty.bean.ConsuMessage;
import com.citcc.api.netty.utils.HexUtil;


public class ConsuEncoder extends SimpleChannelHandler {

    @Override
    public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        // TODO Auto-generated method stub
        ChannelBuffer buffer = buildBuffer((ConsuMessage) e.getMessage());
        if (buffer != null) {
            Channels.write(ctx, e.getFuture(), buffer);
        }
    }
    /**
     * 生成下行报文
     *
     * @param msg
     * @return
     */
    private ChannelBuffer buildBuffer(ConsuMessage msg) {
        int bodyLength = 0;
        if(msg.getMsgBody() !=null){
            bodyLength = msg.getMsgBody().capacity();
        }
        ChannelBuffer buffer = ChannelBuffers.buffer(bodyLength + 7);
        buffer.writeByte(ConsuMessage.MSG_HEAD_1);  //1
        buffer.writeByte(ConsuMessage.MSG_HEAD_2);//头2
        //--------------数据体----------
        if (null != msg.getMsgBody()) {
            buffer.writeBytes(msg.getMsgBody());
        }
        buffer.writeByte(ConsuMessage.MSG_END);//1
        //------------校验和---------
        buffer.writeBytes(HexUtil.SumCheck(buffer.array(),4));//4
        System.out.println("before send ：" + buffer);
        return buffer;
    }

}
